import wx from "weixin-js-sdk";
import _AP from "./ap";
import { getOpenid } from "@/utils/local";
import { wechatLogin, JsSdk } from "@/api/login";
import { stringifyToParams, paramsToStringify } from "@/utils/tools";

/**
 * @description: 判断微信环境
 */
export function isWechat() {
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	return /micromessenger/i.test(window.navigator.userAgent.toLowerCase());
}

/**
 * @description: 微信授权
 */
export async function wechatAuth(options) {
	console.log(options);
	console.log(`${!isWechat() ? "非" : ""}微信环境`, options, getOpenid());
	if (!isWechat() || getOpenid()) return;
	const params = stringifyToParams(window.location.href);
	if (params.code && params.state === (options.state || "weixinAuthorize")) {
		const { code, data } = await wechatLogin({ code: params.code });
		if (code === 0) {
			console.log(data);
		}
		return;
	}
	// 授权配置参数
	const authParams = {
		appid: options.appid,
		redirect_uri: encodeURIComponent(window.location.href.split("?")[0]),
		response_type: "code",
		scope: "snsapi_userinfo", // snsapi_base静默授权 0,snsapi_userinfo用户授权 1
		state: "weixinAuthorize", // 重定向后会带上state参数
	};
	const oAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?${paramsToStringify(
		authParams,
	)}#wechat_redirect`;
	window.location.replace(oAuthUrl);
}

/**
 * @description: 微信jsApi初始化
 */
export async function init(success, fail) {
	if (!isWechat()) {
		fail && fail();
		return;
	}
	// 获取签名
	const params = {
		url: window.location.href,
	};
	const { data } = await JsSdk(params);
	if (data) {
		wx.config({
			debug: false,
			appId: data.appId,
			timestamp: data.timestamp,
			nonceStr: data.nonceStr,
			signature: data.signature,
			jsApiList: ["chooseWXPay", "getBrandWCPayRequest", "updateAppMessageShareData", "updateTimelineShareData"],
		});
		wx.ready(() => {
			success && success();
		});
		wx.error((err) => {
			console.log(err);
			fail && fail();
		});
	}
}

/**
 * @description: 微信支付
 */
export function wxPay(data, callback) {
	wx.chooseWXPay({
		timestamp: data.timeStamp,
		nonceStr: data.nonceStr,
		package: data.package,
		signType: data.signType,
		paySign: data.paySign,
		success(res) {
			callback && callback(res);
		},
		fail(err) {
			console.log(err);
		},
	});
}

/**
 * 微信H5支付
 * @param {*} data
 */
export function WxH5Pay(data, callback) {
	const backUrl = encodeURIComponent(callback);
	const payUrl = `${data.url}&redirect_url=${backUrl}`;
	location.replace(payUrl);
}

/**
 * @description: 支付宝支付
 */
export function Alipay(data) {
	const div = document.createElement("div");
	div.innerHTML = data;
	document.body.appendChild(div);
	document.forms[0].acceptCharset = "utf-8";

	let queryParam = "";
	Array.prototype.slice.call(document.querySelectorAll("input[type=hidden]")).forEach(function (ele) {
		queryParam += `${ele.name}=${encodeURIComponent(ele.value)}&`;
	});
	const gotourl = `${document.forms[0].action}&${queryParam}`;
	_AP.pay(gotourl);
}

/**
 * @description: 支付
 */
export function pay(data) {
	if (isWechat()) {
		wxPay(data);
	} else {
		Alipay(data);
	}
}

/**
 * @description: 分享给朋友
 */
export function shareFriend(options) {
	console.log("updateAppMessageShareData", options);
	wx.ready(function () {
		// 需在用户可能点击分享按钮前就先调用
		wx.updateAppMessageShareData({
			title: options?.title || document.title, // 分享标题
			desc: options?.desc, // 分享描述
			link: options?.link || window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: options?.imgUrl, // 分享图标
			success() {},
			error(err) {
				console.log(`分享失败${err}`);
			},
		});
	});
}

/**
 * @description: 分享给朋友圈
 */
export function shareTimeline(options) {
	console.log("updateTimelineShareData", options);

	// 需在用户可能点击分享按钮前就先调用
	wx.ready(function () {
		wx.updateTimelineShareData({
			title: options?.title || document.title, // 分享标题
			link: options?.link || window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: options?.imgUrl, // 分享图标
			success() {
				// 设置成功
			},
			error(err) {
				console.log(`分享失败${err}`);
			},
		});
	});
}
